package com.iefgames.cs.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mortbay.util.ajax.Continuation;
import org.mortbay.util.ajax.ContinuationSupport;

import com.iefgames.cs.manager.PopleManager;
import com.iefgames.cs.pople.Cs;
import com.iefgames.cs.pople.Pople;
import com.iefgames.cs.pople.Us;

public class Comet extends HttpServlet {
	private static final long serialVersionUID = 1131902499354921788L;
	
	private static Log logger = LogFactory.getLog(Comet.class);
	
	@SuppressWarnings("unused")
	private static Map<String, Continuation> CometMap = new HashMap<String, Continuation>();
	
	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		Enumeration<String> names = request.getParameterNames();
		
		String name = null;
		ArrayList<String> params = new ArrayList<String>();
		while (names.hasMoreElements()) {
			params.add((name = names.nextElement()) + "=" + request.getParameter(name));
		}
		
		String uuid = request.getParameter("uuid");
		
		if (StringUtils.EMPTY.equals(uuid)
				|| uuid.length() != 32) {
			return ;
		}
		
		Pople p = PopleManager.get(uuid);
		
		Continuation continuation = ContinuationSupport.getContinuation(request, null);
		logger.debug("------>" + request.getRequestURI() + " " + params.toString() + "--------" + continuation.isNew());
		if (continuation.isNew()) {
			if (p == null) {
				//全新的comet
				if (Boolean.parseBoolean((String) request.getParameter("isCs"))) {
					p = new Cs(uuid);
				} else {
					p = new Us(uuid);
				}
			}
			
			p.setCometTime(Long.parseLong(request.getParameter("timestamp")));
			p.newcomet(request, response);
		}
		
		p.fire(request, response);
	}

}
